import { PayPalButtons } from '@paypal/react-paypal-js';
import {useState} from 'react';
import { Modal } from 'antd';
import router from "next/router";
import { request } from "../../utils/request";
import { basePath } from '../../utils/tool';
const PayPalCheckoutButton = (props) => {
    
    const { product } = props;
    
    const [paidFor,setPaidFor] = useState();
    const [error,setError] = useState(null)
    const handleApprove = async (orderId)=>{
       console.log('orderid',orderId)
        //支付成功
        if(props.orderNo){
            const ret = await request(`${basePath()}/api/order/updatePayStatus`,{
                outTradeNo:orderId,
                orderNo:props.orderNo
            })
        }
        
        setPaidFor(true)
        //失败

    }
    if(paidFor){
        //支付成功提示
        router.replace('/account');
    }
    if(error){
        //display error message
        console.log('error',error)
        alert(error)
    }
    return <PayPalButtons
        onClick={(data,actions)=>{
            console.log('onclice',data)
            console.log('onclice',actions)
            const hasAlreadyBuy = false;
            if(hasAlreadyBuy){
                setError('you alread bought this goods');
                return actions.reject()
            } else {
                return actions.resolve()
            }
        }} 
        createOrder={(data, actions) => {
            return actions.order.create({
                purchase_units: props.units,
            })
        }}
        onApprove={async (data, actions) => {
            const order = await actions.order.capture();
            console.log('order',order)
            handleApprove(data.orderID)
        }}
        onCancel={()=>{
            console.log('cancle pay')
        }}
        onError={(err)=>{
            setError(err);
            console.error('err',err)
        }}
        
    />
}
export default PayPalCheckoutButton